#!/usr/bin/env bash
#
# This is a wrapper to allow BDR to run pg_regress etc with a custom
# config file, the needed extensions installed, etc. It works around the
# lack of needed pg_regress features in 9.4.
#
# Don't call this directly, use "make regresscheck", "make isolationcheck", etc
# or just "make check"
# 

set -e
#set -x

BINDIR=$(@PG_CONFIG@ --bindir)
REGRESS_BASE=$(@PG_CONFIG@ --pkglibdir)/pgxs/
DBNAME=regression

mkdir -p tmp_check
rm -rf tmp_check/data
rm -rf tmp_check/postmaster.log
rm -rf tmp_check/initdb.log
mkdir tmp_check/data

set +e
for getoptbin in $(which getopt) /usr/bin/getopt /usr/local/bin/getopt ; do
  [ -x "${getoptbin}" ] || continue
  "${getoptbin}" -T >/dev/null ; ret=$?
  if [ "${ret}" -eq 4 ] ; then
    EXTGETOPT="${getoptbin}"
    break;
  fi
done
if [ -z "${EXTGETOPT}" ] ; then
  echo "no compatible (extended) getopt found" >&2
  exit 1
fi
set -e

PARSEOPTS=$("${EXTGETOPT}" \
    --longoptions testbinary: \
    --longoptions dbname: \
    --longoptions config: \
    -o 'h' -- "$@")

eval set -- "$PARSEOPTS"


usage() {
    echo "run_tests -h --testbinary binary LIST OF TESTS"
    exit 1
}

while true ; do
    case "$1" in
	-h) usage; shift;;
	--testbinary) TESTBINARY="$2"; shift;shift;;
	--dbname) DBNAME="$2"; shift;shift;;
	--config) CONFIGFILE="$2"; shift;shift;;
	--) shift ; break ;;
	*) echo "unknown option $1"; exit 1;;
    esac
done

SOCKET=$(pwd)/tmp_check
PORT=5440
OPTIONS="-c config_file=${CONFIGFILE}"
OPTIONS="$OPTIONS -c unix_socket_directories=$SOCKET"
OPTIONS="$OPTIONS -c listen_addresses=''"
OPTIONS="$OPTIONS -c port=${PORT}"

export PGHOST=$SOCKET
export PGPORT=$PORT

# create new data directory
$BINDIR/initdb --nosync tmp_check/data > tmp_check/initdb.log 2>&1

# install trap to shutdown server at failure/exit
trap "$BINDIR/pg_ctl stop -w -D tmp_check/data" INT QUIT TERM EXIT

#start server
$BINDIR/pg_ctl start -w -D tmp_check/data -o "$OPTIONS" -c -l tmp_check/postmaster.log

$REGRESS_BASE/$TESTBINARY \
    --host $SOCKET \
    --port $PORT \
    --dbname $DBNAME \
    --inputdir=@srcdir@ \
    "$@"

exit 0
